package com.sk.security.userdetails.client;

import com.sk.dto.SysOauthClientDto;
import com.sk.enums.PasswordEncoderTypeEnum;
import com.sk.res.CommonResponseDto;
import com.sk.security.feign.SystemBaseFeignService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author jiaok
 * @Date 2024-04-24 14:15
 */
@Service
@RequiredArgsConstructor
public class ClientDetailsServiceImpl  implements ClientDetailsService {

    @Resource
    private SystemBaseFeignService systemBaseFeignService;

    @Override
    @Cacheable(cacheNames = "aouth2", key = "'oauth-client:'+#clientId")
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        CommonResponseDto<SysOauthClientDto> result = systemBaseFeignService.selectOAuth2ClientById(clientId);
        if (CommonResponseDto.isSuccess(result)){
            SysOauthClientDto sysOauthClientDto = result.getData();
            BaseClientDetails clientDetails = new BaseClientDetails(
                    sysOauthClientDto.getClientId(),
                    sysOauthClientDto.getResourceIds(),
                    sysOauthClientDto.getScope(),
                    sysOauthClientDto.getAuthorizedGrantTypes(),
                    sysOauthClientDto.getAuthorities(),
                    sysOauthClientDto.getWebServerRedirectUri()
            );
            clientDetails.setClientSecret(PasswordEncoderTypeEnum.NOOP.getPrefix() + sysOauthClientDto.getClientSecret());
            clientDetails.setAccessTokenValiditySeconds(sysOauthClientDto.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(sysOauthClientDto.getRefreshTokenValidity());
            return clientDetails;
        }else {
            throw new NoSuchClientException("非法客户端,id: " + clientId);
        }
    }

}
